﻿using Dapper;
using DDD.Core.CQRS;
using DDD.Core.Result;
using System.Text;

namespace DDD.Application.Queries.UserQuery.GetUserPage;

internal class GetUserPageQueryHandler : QueryHandler<GetUserPageQuery, ApiResult<GetUserPageVO>, GetUserPageVO>
{
    private readonly IDBConnectionFactory _dBConnectionFactory;

    public GetUserPageQueryHandler(IDBConnectionFactory dBConnectionFactory) : base(dBConnectionFactory)
    {
        _dBConnectionFactory = dBConnectionFactory;
    }

    public override async Task<ApiResult<GetUserPageVO>> Handle(GetUserPageQuery request, CancellationToken cancellationToken)
    {
        using var dbConnection = _dBConnectionFactory.GetDbConnection();

        string whereSql = buildWhereSql();

        string totalSql = $"select count(1) from User {whereSql} ";
        int total = await dbConnection.ExecuteScalarAsync<int>(totalSql, request);
        if (total <= 0)
            return ApiResult<GetUserPageVO>.Success(new GetUserPageVO());

        string dataSql = $"select * from User {whereSql} limit {request.PageSize} offset {(request.PageIndex - 1) * request.PageSize}";
        var data = await dbConnection.QueryAsync<UserDto>(dataSql, request);

        return ApiResult<GetUserPageVO>.Success(new GetUserPageVO()
        {
            Data = data,
            PageIndex = request.PageIndex,
            PageSize = request.PageSize,
            Total = total
        });

        string buildWhereSql()
        {
            StringBuilder whereStringBuilder = new StringBuilder();
            whereStringBuilder.Append(" where ");
            if (!string.IsNullOrEmpty(request.UserName))
                whereStringBuilder.Append($" username like '{request.UserName}%' ");

            return whereStringBuilder.ToString();
        }
    }
}
